package com.fast.modules.acd.service.impl;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fast.modules.acd.entity.Seat;
import com.fast.modules.acd.entity.SeatVo;
import com.fast.modules.acd.service.SeatService;
import com.fast.modules.acd.service.SeatStorageService;
import com.fast.modules.websocket.service.UserService;

/**
 * 坐席的服务类
 * @author yaoyuquan
 *
 */
@Service
public class SeatServiceImpl implements SeatService {
	
	@Autowired
	SeatStorageService seatStorageService;
	
	@Autowired
	UserService userService;

	/**
	 * 坐席上线，把坐席的对应信息放到内存的map中
	 */
	@Override
	public boolean online(String seatID, List<String> skills) {

		boolean result = false;

		if (!seatStorageService.containsKey(seatID)) {
			
			seatStorageService.put(seatID, new Seat(seatID, skills));
			result = true;
		}

		return result;
	}

	/**
	 * 坐席下线
	 */
	@Override
	public boolean offline(String seatID) {

		boolean result = false;

		if (seatStorageService.containsKey(seatID)) {
			seatStorageService.remove(seatID);
			result = true;
		}

		return result;
	}

	/**
	 * 显示坐席当前全部的会话信息
	 */
	@Override
	public List<SeatVo> status() {
		
		Map<String, Seat> map = seatStorageService.map();
		
		Map<String, List<String>> session = userService.getSeatSession();
		
		List<SeatVo> list = map.entrySet().stream().map(Entry::getValue).map(SeatVo::new).collect(ArrayList::new, (ll,vo) -> {
			vo.setClients(session.get(vo.getId()));
			ll.add(vo);
		}, ArrayList::addAll);
		
		return list;
	}


	@Override
	public boolean support(String skill) {
		
		boolean result = false;

		HashSet<String> set = seatStorageService.stream().map(seat -> {
			return seat.getSkills();
		}).collect(HashSet<String>::new, HashSet<String>::addAll, HashSet<String>::addAll);
		
		if(set.contains(skill)) {
			result = true;
		}

		return result;
	}

	@Override
	public void busy(String seatID) {
		
		seatStorageService.get(seatID).setBusy(true);
		
	}

	@Override
	public void available(String seatID) {
		
		seatStorageService.get(seatID).setBusy(false);
	}

	@Override
	public void hangup(String seatID, String clientID) {
		userService.getOnlineRelation().remove(clientID);
		
		//设置坐席的空闲时间
		if(userService.getSeatSessionSize(seatID) == 0 && seatStorageService.containsKey(seatID)) {
			seatStorageService.get(seatID).setIdleTime(System.currentTimeMillis());
		}
	}

	@Override
	public void hangup(String clientID) {

		if(userService.getOnlineRelation().containsKey(clientID)) {
			hangup(userService.getOnlineRelation().get(clientID), clientID);
		}
		
	}

}
